package deanandjames.sound;

import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;
import java.io.IOException;

public class MidiInfo {
	private final String filename;
	private boolean isLooping = false;
	private final String name;
	private Sequence sequence = null;
	private final Sequencer sequencer;

	public MidiInfo(String name, String filename, Sequencer sequencer) {
		this.name = name;
		this.filename = "Sounds/" + filename;
		this.sequencer = sequencer;
		loadMidi();
	}

	public String getName() {
		return name;
	}

	public void pause() {
		if (sequencer != null && sequence != null) {
			if (sequencer.isRunning()) {
				sequencer.stop();
			}
		}
	}

	public void play(boolean toLoop) {
		if (sequencer != null && sequence != null) {
			try {
				sequencer.setSequence(sequence);
				sequencer.setTickPosition(0);
				isLooping = toLoop;
				sequencer.start();
			} catch (final InvalidMidiDataException e) {
				System.out.println("Corrupted/invalid midi file: " + filename);
			}
		}
	}

	public void resume() {
		if (sequencer != null && sequence != null) {
			sequencer.start();
		}
	}

	public void stop() {
		if (sequencer != null && sequence != null) {
			isLooping = false;
			if (!sequencer.isRunning()) {
				sequencer.start();
			}
			sequencer.setTickPosition(sequencer.getTickLength());
		}
	}

	public boolean tryLooping() {
		if (sequencer != null && sequence != null) {
			if (sequencer.isRunning()) {
				sequencer.stop();
			}
			sequencer.setTickPosition(0);
			if (isLooping) {
				sequencer.start();
				return true;
			}
		}
		return false;
	}

	private void loadMidi() {
		try {
			sequence = MidiSystem.getSequence(getClass().getResource(filename));
		} catch (final InvalidMidiDataException e) {
			System.out.println("Unreadable/unsupported midi file: " + filename);
		} catch (final IOException e) {
			System.out.println("Could not read: " + filename);
		} catch (final Exception e) {
			System.out.println("Problem with " + filename);
		}
	}
}
